<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>手机桌面网格布局</title>
  <style>
    html,
    body {
      padding: 10px;
      margin: 0;
      width: 100%;
      box-sizing: border-box;
    }

    .grid-box {
      width: 200px;
      height: 400px;
      border: 1px solid #999;
      margin: 20px;
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      grid-template-rows: repeat(8, 1fr);
      gap: 6px;
      padding: 6px;
      grid-auto-flow: dense;
    }

    .grid-box>div {
      background-color: bisque;
      border-radius: 4px;
      border: 1px solid #ccc;
    }

    /* 
      1x1 1x2 1x3
      2x1 2x2 2x3
      3x1 3x2 3x3
     */

    .grid-box-item-1 {
      /* 1x2 */
      grid-column-end: span 2;
    }

    .grid-box-item-2 {
      /* 2x1 */
      grid-row-end: span 2;
    }

    .grid-box-item-3 {
      /* 2x2 */
      grid-column-end: span 2;
      grid-row-end: span 2;
    }

    .grid-box-item-4 {
      /* 3x1 */
      grid-column-end: span 3;
    }

    .grid-box-item-5 {
      /* 3x2 */
      grid-column-end: span 3;
      grid-row-end: span 2;
    }

    .grid-box-item-6 {
      /* 3x3 */
      grid-column-end: span 3;
      grid-row-end: span 3;
    }
  </style>
</head>

<body>
  <button onclick="randomItem()">随机</button>
  <div class="grid-box" id="box"></div>

  <script>

    // 需求：假设桌面的图标或小组件，可以选择1x1, 1x2, 2x1, 2x2四种效果。
    // 所以我们可以先设置三种大小的子节点空间，因为默认是1x1，所以1x1不需要单独这种。有了这几个class我们创建子节点的时候，只要往上面添加这个对应的class就能实现对应的效果。
    let boxEl = document.getElementById('box');

    function randomItem() {
      console.log('随机');
      let styleArr = [0, 0, 0, 0, 1, 1, 2, 3];
      styleArr = styleArr.sort(() => {
        return Math.random() > 0.5 ? 1 : -1;
      })
      console.log(styleArr);
      let itemsEl = '';
      for (let i = 0; i < styleArr.length; i++) {
        itemsEl += `<div class="grid-box-item-${styleArr[i]}">${i + 1}</div>`;
      }
      boxEl.innerHTML = itemsEl;
    }

    randomItem();
  </script>
</body>

</html>